import json
import requests

from volcengine.base.Request import Request


g_knowledge_base_domain = "api-knowledgebase.mlp.cn-beijing.volces.com"

def prepare_request(api_key, method, path, params=None, data=None, doseq=0):
    if params:
        for key in params:
            if (
                    isinstance(params[key], int)
                    or isinstance(params[key], float)
                    or isinstance(params[key], bool)
            ):
                params[key] = str(params[key])
            elif isinstance(params[key], list):
                if not doseq:
                    params[key] = ",".join(params[key])
    r = Request()
    r.set_shema("http")
    r.set_method(method)
    r.set_connection_timeout(10)
    r.set_socket_timeout(10)
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json;charset=UTF-8",
        "Host": g_knowledge_base_domain,
        'Authorization': f'Bearer {api_key}'
    }
    r.set_headers(headers)
    if params:
        r.set_query(params)
    r.set_host(g_knowledge_base_domain)
    r.set_path(path)
    if data is not None:
        r.set_body(json.dumps(data))
    return r


def knowledge_service_chat(api_key: str, service_id: str, query: str):
    method = "POST"
    path = "/api/knowledge/service/chat"
    request_params = {
    "service_resource_id": service_id,
    "messages":[
        {
            "role": "user",
            "content":query
        }
    ],
    "stream": False
    }

    info_req = prepare_request(api_key=api_key, method=method, path=path, data=request_params)
    rsp = requests.request(
        method=info_req.method,
        url="http://{}{}".format(g_knowledge_base_domain, info_req.path),
        headers=info_req.headers,
        data=info_req.body
    )
    rsp.encoding = "utf-8"
    return rsp


def construct_user_prompt_and_knowledge(api_key: str, service_id: str, user_message):
    # RAG匹配知识
    knowledge_rsp = knowledge_service_chat(api_key, service_id, user_message.get("content"))
    if knowledge_rsp.status_code == 200:
        knowledge_json = json.loads(knowledge_rsp.text)
        result_list = knowledge_json["data"]["result_list"]
        for result in result_list:
            if result["score"] > 0.3:
                # 这里比较粗暴的直接将匹配到的知识添加到系统提示词中，建议大家自己实现时可以尝试更多不同提示词工程方案
                user_message['content'] = user_message['content'] + "以下是通过RAG自动匹配到的信息：\n" + result["content"]
    return user_message